package com.jstyle.beatecg.fragment;

import android.content.Context;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.jstyle.beatecg.R;
import com.jstyle.beatecg.adapter.HistoryFragmentAdapter;
import com.jstyle.beatecg.base.BaseFragment;
import com.jstyle.beatecg.util.DateUtil;
import com.jstyle.beatecg.util.ScreenUtils;

import java.util.Date;
import java.util.Locale;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link InfoFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class InfoFragment extends BaseFragment {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.tablayout_history)
    TabLayout tablayoutHistory;
    @BindArray(R.array.tablayout_title)
    String[] arrayTitle;
    @BindArray(R.array.tablayout_content)
    String[] arrayContent;
    Unbinder unbinder;
    @BindView(R.id.ll_title)
    LinearLayout llTitle;
    @BindView(R.id.tablayout_history_content)
    TabLayout tablayoutHistoryContent;
    @BindView(R.id.history_viewpager)
    FrameLayout historyViewpager;
    @BindView(R.id.bt_data_month_preMonth)
    ImageView btDataMonthPreMonth;
    @BindView(R.id.bt_data_month_nextMonth)
    ImageView btDataMonthNextMonth;
    @BindView(R.id.bt_data_month_date)
    Button btDataMonthDate;
    public int dateType = 0;
    int dataType=0;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private HistoryFragmentAdapter historyFragmentAdapter;
    private String thisMonth;
    private String[] monthDates;
    private String[] thisWeek;
    private String todayString;
    private int position;

    public InfoFragment() { }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment InfoFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static InfoFragment newInstance(String param1, String param2) {
        InfoFragment fragment = new InfoFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_info, container, false);
        unbinder = ButterKnife.bind(this, view);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            ScreenUtils.setStatusBarColor(llTitle, android.R.color.transparent);
        }
        initData();
        initView();
        return view;
    }

    private void initData() {
        thisMonth = DateUtil.getMonthString("", DateUtil.this_month);
        monthDates = DateUtil.getThisMonth();
        thisWeek = DateUtil.getTodayWeek(0);
        todayString = DateUtil.getDefaultFormatTime(new Date());
    }

    private void initView() {

        tablayoutHistory.setTabMode(TabLayout.MODE_FIXED);
        tablayoutHistory.setTabGravity(TabLayout.GRAVITY_FILL);
        tablayoutHistory.setSelectedTabIndicatorColor(Color.parseColor("#05a0ff"));
        for (String title : arrayTitle) {
            tablayoutHistory.addTab(tablayoutHistory.newTab().setText(title));
        }
        tablayoutHistory.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                dateType = tab.getPosition();
                showDate();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

        tablayoutHistoryContent.setTabMode(TabLayout.MODE_FIXED);
        tablayoutHistoryContent.setTabGravity(TabLayout.GRAVITY_FILL);
        tablayoutHistoryContent.setSelectedTabIndicatorColor(Color.parseColor("#05a0ff"));
        historyFragmentAdapter = new HistoryFragmentAdapter(getChildFragmentManager(), arrayContent);
        tablayoutHistoryContent.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                 position = tab.getPosition();
                Fragment fragment = (Fragment) historyFragmentAdapter.instantiateItem(historyViewpager, position);
                historyFragmentAdapter.setPrimaryItem(historyViewpager, position, fragment);
                historyFragmentAdapter.finishUpdate(historyViewpager);

            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        for (int i = 0; i < arrayContent.length; i++) {
            String title = arrayContent[i];
            tablayoutHistoryContent.addTab(tablayoutHistoryContent.newTab().setText(title), i == 0);
        }
        showDate();
    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.bt_data_month_preMonth, R.id.bt_data_month_nextMonth})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.bt_data_month_preMonth:
                showPreDate();
                break;
            case R.id.bt_data_month_nextMonth:
                showNextDate();
                break;
        }
    }
    private void showDate(){
        String showDate="";
        switch (dateType) {
            case 0:
                showDate=todayString;
                break;
            case 1:
                showDate=thisWeek[0]+"-"+thisWeek[6];
                break;
            case 2:
                showDate=getShowDate(monthDates[0]);
                break;
        }
        btDataMonthDate.setText(showDate);
        Fragment fragment = (Fragment) historyFragmentAdapter.instantiateItem(historyViewpager, position);
        switch (position){
            case 0:
                ((ExerciseHistoryFragment)fragment).updateData();
                break;
            case 1:
                ((HealthHistoryFragment)fragment).updateData();
                break;
            case 2:
                ((HrvReportHistoryFragment)fragment).updateData();
                break;
        }
    }
    private void showPreDate() {
        switch (dateType) {
            case 0:
                todayString = DateUtil.getYesterdayDateString(todayString);
                break;
            case 1:
                thisWeek=DateUtil.getWeekString(thisWeek[0], DateUtil.lastWeek);
                break;
            case 2:
                thisMonth = DateUtil.getMonthString(thisMonth, DateUtil.last_month);
                monthDates = DateUtil.getLastMonth(monthDates[0]);
                break;
        }
        showDate();
    }

    private void showNextDate() {
        switch (dateType) {
            case 0:
                todayString = DateUtil.getTomorrowDateString(todayString);
                break;
            case 1:
                thisWeek=DateUtil.getWeekString(thisWeek[6], DateUtil.nextWeek);
                break;
            case 2:
                thisMonth = DateUtil.getMonthString(thisMonth, DateUtil.next_month);
                monthDates = DateUtil.getNextMonth(monthDates[0]);
                break;
        }
       showDate();
    }

    public String[] getMonthDate(){
        return monthDates;
    }
    public String[] getThisWeek(){
        return thisWeek;
    }
    public String getTodayString(){
        return todayString;
    }
    private String getShowDate(String monthString){
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        long time=DateUtil.getDateLong(monthString);
        String format="";
        if(language.equals("zh")){
            format="yyyy-MM";
        }else{
            format="MM-yyyy";
        }
        return DateUtil.getFormatTimeString(time,format);
    }
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
